#include "histogramRGB.h"
#include <iostream>

HistogramRGB::HistogramRGB(): Histogram()
{
    histogramR=new unsigned int[256];
    histogramG=new unsigned int[256];
    histogramB=new unsigned int[256];
}

HistogramRGB::HistogramRGB(QImage* mi): Histogram(mi)
{
    histogramR=new unsigned int[256];
    histogramG=new unsigned int[256];
    histogramB=new unsigned int[256];
}

HistogramRGB::~HistogramRGB()
{
    delete []histogramR;
    delete []histogramG;
    delete []histogramB;
}

void HistogramRGB::calcHistogram()
{
    if(ownerImage==NULL)
        return;
    else
    {
        for(int i=0;i<256;i++)
        {
            histogramR[i]=0;
            histogramG[i]=0;
            histogramB[i]=0;
        }
        for(int x=0;x<ownerImage->width();x++)
            for(int y=0;y<ownerImage->height();y++)
            {
                histogramR[qRed(ownerImage->pixel(x,y))]++;
                histogramG[qGreen(ownerImage->pixel(x,y))]++;
                histogramB[qBlue(ownerImage->pixel(x,y))]++;
            }
            calcHistImage();
    }
}

void HistogramRGB::calcHistImage()
{
    int width=512;
    int height=300;
    int fracc=width/256;
    if(histImage==NULL)
        histImage=new QImage(width,height,QImage::Format_RGB32);
    unsigned long max=0;
    for(int i=0;i<256;i++)
    {
        if(histogramR[i]>max)
            max=histogramR[i];
        if(histogramG[i]>max)
            max=histogramG[i];
        if(histogramB[i]>max)
            max=histogramB[i];
    }
    std::cout << max << std::endl;
    for(int x=0;x<histImage->width();x++)
        for(int y=0;y<histImage->height();y++)
            histImage->setPixel(x,y,qRgb(255,255,255));
    for(int i=0;i<width;i++)
    {
        int hred=(height-1)*(1.0-histogramR[i/fracc]/(double)max);
        int hgreen=(height-1)*(1.0-histogramG[i/fracc]/(double)max);
        int hblue=(height-1)*(1.0-histogramB[i/fracc]/(double)max);
        for(int j=0;j<height;j++)
        {
            int r=0;
            int g=0;
            int b=0;
            if(j>hred)
            {
                r+=255;
                g+=96;
                b+=96;
            }
            if(j>hgreen)
            {
                r+=96;
                g+=255;
                b+=96;
            }
            if(j>hblue)
            {
                r+=96;
                g+=96;
                b+=255;
            }
            if(r>225) r=255;
            if(g>225) g=255;
            if(b>255) b=255;
            if(j==hred)
            {
                r=255;
                g=0;
                b=0;
            }
            if(j==hgreen)
            {
                r=0;
                g=255;
                b=0;
            }
            if(j==hblue)
            {
                r=0;
                g=0;
                b=255;
            }
            histImage->setPixel(i,j,qRgb(r,g,b));
        }
    }
}

